package org.llc.bpmn.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.llc.bpmn.model.vo.PageVo;
import org.llc.bpmn.model.vo.HistoryProcess;
import org.llc.bpmn.model.vo.PurchaseTask;
import org.llc.bpmn.model.vo.Result;
import org.llc.bpmn.model.po.PurchaseBpm;
import org.llc.bpmn.service.PurchaseBpmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "采购流程接口")
@Controller
public class BpmPurchaseController {


    @Autowired
    RuntimeService runservice;

    @Autowired
    TaskService taskservice;

    @Autowired
    HistoryService histiryservice;

    @Autowired
    PurchaseBpmService purchaseservice;


    /*
    =============================审批================================
     */
	@ApiOperation("发起一个采购流程")
	@RequestMapping(value = "startpurchase", method = RequestMethod.POST)
	@ResponseBody
	Result startpurchase(@RequestParam("itemlist") String itemlist, @RequestParam("total") BigDecimal total, HttpSession session) {
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<>();
		variables.put("starter", userid);
		purchaseservice.startWorkflow(itemlist, total, userid, variables);
		return new Result("sucess");
	}






	@ApiOperation("采购经理审批")
	@RequestMapping(value = "task/purchasemanagercomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result purchasemanagercomplete(HttpSession session,
										  @PathVariable("taskid") String taskid,
										  HttpServletRequest req) {
		String purchaseauditi = req.getParameter("purchaseauditi");
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<>();
		variables.put("purchaseauditi", purchaseauditi);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return new Result("ok");
	}



	@ApiOperation("调整采购申请待办")
	@RequestMapping(value = "task/updateapplycomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result updateapplycomplete(HttpSession session,
									  @PathVariable("taskid") String taskid,
									  HttpServletRequest req) {
		String updateapply = req.getParameter("updateapply");
		String userid = (String) session.getAttribute("username");
		if (updateapply.equals("true")) {
			String itemlist = req.getParameter("itemlist");
			String total = req.getParameter("total");
			Task task = taskservice.createTaskQuery().taskId(taskid).singleResult();
			String instanceid = task.getProcessInstanceId();
			ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
			String businesskey = ins.getBusinessKey();
			PurchaseBpm p = purchaseservice.getPurchase(Integer.parseInt(businesskey));
			p.setItemlist(itemlist);
			p.setTotal(new BigDecimal(Integer.parseInt(total)));
			purchaseservice.updatePurchase(p);
		}
		Map<String, Object> variables = new HashMap<>();
		variables.put("updateapply", Boolean.parseBoolean(updateapply));
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return new Result("ok");
	}


	@ApiOperation("完成财务审批待办")
	@RequestMapping(value = "task/financecomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result financecomplete(HttpSession session,
								  @RequestParam("total") String total,
								  @PathVariable("taskid") String taskid,
								  HttpServletRequest req) {
		String finance = req.getParameter("finance");
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<>();
		variables.put("finance", finance);
		if (finance.equals("true"))
			variables.put("money", total);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return new Result("ok");
	}


	@ApiOperation("完成总经理审批待办")
	@RequestMapping(value = "task/managercomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result managercomplete(HttpSession session,
								  @RequestParam("total") String total,
								  @PathVariable("taskid") String taskid,
								  HttpServletRequest req) {
		String manager = req.getParameter("manager");
		String userid = (String) session.getAttribute("username");
		Map<String, Object> variables = new HashMap<>();
		variables.put("manager", manager);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return new Result("ok");
	}

	@ApiOperation("完成出纳付款待办")
	@RequestMapping(value = "task/paycomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result paycomplete(HttpSession session,
							  @PathVariable("taskid") String taskid) {
		String userid = (String) session.getAttribute("username");
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid);
		return new Result("ok");
	}


	@ApiOperation("完成收货确认待办任务")
	@RequestMapping(value = "task/receivecomplete/{taskid}", method = RequestMethod.POST)
	@ResponseBody
	public Result receivecomplete(HttpSession session,
								  @PathVariable("taskid") String taskid) {
		String userid = (String) session.getAttribute("username");
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid);
		return new Result("ok");
	}

	/*
   =============================审批列表================================
    */


    @ApiOperation("我发起的采购流程")
    @RequestMapping(value = "mypurchaseprocess", method = RequestMethod.POST)
    @ResponseBody
    public PageVo<PurchaseBpm> mypurchaseprocess(HttpSession session,
                                                 @RequestParam("current") int current,
                                                 @RequestParam("rowCount") int rowCount) {
        String username = (String) session.getAttribute("username");
        PageVo<PurchaseBpm> grid = new PageVo<>();
        grid.setRowCount(current);
        grid.setCurrent(rowCount);
        List<PurchaseBpm> list = purchaseservice.pageList(username, current, rowCount);
        for (PurchaseBpm apply : list) {
            ProcessInstance process = runservice.createProcessInstanceQuery().processDefinitionKey("purchase").processInstanceBusinessKey(String.valueOf(apply.getId())).singleResult();
            if (process == null) {
                apply.setState("已结束");
                apply.setActivityid("无");
            } else {
                apply.setState("运行中");
                apply.setActivityid(process.getActivityId());
            }
        }
        grid.setTotal(purchaseservice.list(username).size());
        grid.setRows(list);
        return grid;
    }



    @ApiOperation("获取采购经理待办列表")
    @RequestMapping(value = "/puchasemanagertasklist", method = RequestMethod.POST)
    @ResponseBody
    PageVo<PurchaseTask> puchasemanagertasklist(HttpSession session,
                                                @RequestParam("current") int current,
                                                @RequestParam("rowCount") int rowCount) {
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setTotal(0);
        grid.setRows(new ArrayList<>());
        int firstrow = (current - 1) * rowCount;
        List<PurchaseTask> results = new ArrayList<>();
        List<Task> tasks = taskservice.createTaskQuery().taskCandidateGroup("采购经理").listPage(firstrow, rowCount);
        long totaltask = taskservice.createTaskQuery().taskCandidateGroup("采购经理").count();
        for (Task task : tasks) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            results.add(vo);
        }
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setRows(results);
        grid.setTotal((int) totaltask);
        grid.setRows(results);
        return grid;
    }


    @ApiOperation("获取调整采购申请待办列表")
    @RequestMapping(value = "updatepurchaseapply", method = RequestMethod.POST)
    @ResponseBody
    public PageVo<PurchaseTask> updateapply(HttpSession session,
                                            @RequestParam("current") int current,
                                            @RequestParam("rowCount") int rowCount) {
        int firstrow = (current - 1) * rowCount;
        String userid = (String) session.getAttribute("username");
        TaskQuery query = taskservice.createTaskQuery().processDefinitionKey("purchase").taskCandidateOrAssigned(userid).taskDefinitionKey("updateapply");
        long total = query.count();
        List<Task> list = query.listPage(firstrow, rowCount);
        List<PurchaseTask> plist = new ArrayList<>();
        for (Task task : list) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            plist.add(vo);
        }
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setTotal((int) total);
        grid.setRows(plist);
        return grid;
    }


    @ApiOperation("获取已完成采购流程历史数据")
    @RequestMapping(value = "getfinishpurchaseprocess", method = RequestMethod.POST)
    @ResponseBody
    public PageVo<HistoryProcess> getHistory(HttpSession session,
                                             @RequestParam("current") int current,
                                             @RequestParam("rowCount") int rowCount) {
        String userid = (String) session.getAttribute("username");
        HistoricProcessInstanceQuery process = histiryservice.createHistoricProcessInstanceQuery().processDefinitionKey("purchase").startedBy(userid).finished();
        int total = (int) process.count();
        int firstrow = (current - 1) * rowCount;
        List<HistoricProcessInstance> info = process.listPage(firstrow, rowCount);
        List<HistoryProcess> list = new ArrayList<>();
        for (HistoricProcessInstance history : info) {
            HistoryProcess his = new HistoryProcess();
            String bussinesskey = history.getBusinessKey();
            PurchaseBpm apply = purchaseservice.getPurchase(Integer.parseInt(bussinesskey));
            his.setPurchaseapply(apply);
            his.setBusinessKey(bussinesskey);
            his.setProcessDefinitionId(history.getProcessDefinitionId());
            list.add(his);
        }
        PageVo<HistoryProcess> grid = new PageVo<>();
        grid.setRowCount(current);
        grid.setCurrent(rowCount);
        grid.setTotal(total);
        grid.setRows(list);
        return grid;
    }

    @ApiOperation("获取财务审批待办列表")
    @RequestMapping(value = "/financetasklist", method = RequestMethod.POST)
    @ResponseBody
    PageVo<PurchaseTask> financetasklist(HttpSession session,
                                         @RequestParam("current") int current,
                                         @RequestParam("rowCount") int rowCount) {
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        int firstrow = (current - 1) * rowCount;
        List<PurchaseTask> results = new ArrayList<>();
        List<Task> tasks = taskservice.createTaskQuery().taskCandidateGroup("财务管理员").listPage(firstrow, rowCount);
        long totaltask = taskservice.createTaskQuery().taskCandidateGroup("财务管理员").count();
        for (Task task : tasks) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            results.add(vo);
        }
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setTotal((int) totaltask);
        grid.setRows(results);
        return grid;
    }



    @ApiOperation("获取总经理审批待办列表")
    @RequestMapping(value = "/managertasklist", method = RequestMethod.POST)
    @ResponseBody
    PageVo<PurchaseTask> managertasklist(HttpSession session,
                                         @RequestParam("current") int current,
                                         @RequestParam("rowCount") int rowCount) {
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        int firstrow = (current - 1) * rowCount;
        List<PurchaseTask> results = new ArrayList<>();
        List<Task> tasks = taskservice.createTaskQuery().taskCandidateGroup("总经理").listPage(firstrow, rowCount);
        long totaltask = taskservice.createTaskQuery().taskCandidateGroup("总经理").count();
        for (Task task : tasks) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            results.add(vo);
        }
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setTotal((int) totaltask);
        grid.setRows(results);
        return grid;
    }


    @ApiOperation("获取出纳付款待办列表")
    @RequestMapping(value = "/paytasklist", method = RequestMethod.POST)
    @ResponseBody
    PageVo<PurchaseTask> paytasklist(HttpSession session,
                                     @RequestParam("current") int current,
                                     @RequestParam("rowCount") int rowCount) {
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        int firstrow = (current - 1) * rowCount;
        List<PurchaseTask> results = new ArrayList<>();
        List<Task> tasks = taskservice.createTaskQuery().taskCandidateGroup("出纳员").listPage(firstrow, rowCount);
        long totaltask = taskservice.createTaskQuery().taskCandidateGroup("出纳员").count();
        for (Task task : tasks) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            results.add(vo);
        }
        grid.setCurrent(rowCount);
        grid.setRowCount(current);
        grid.setTotal((int) totaltask);
        grid.setRows(results);
        return grid;
    }


    @ApiOperation("获取收货确认待办列表")
    @RequestMapping(value = "/receivetasklist", method = RequestMethod.POST)
    @ResponseBody
    PageVo<PurchaseTask> receivetasklist(HttpSession session,
                                         @RequestParam("current") int current,
                                         @RequestParam("rowCount") int rowCount) {
        int firstrow = (current - 1) * rowCount;
        String userid = (String) session.getAttribute("username");
        TaskQuery query = taskservice.createTaskQuery().processDefinitionKey("purchase").taskCandidateOrAssigned(userid).taskDefinitionKey("receiveitem");
        long total = query.count();
        List<Task> tasks = query.listPage(firstrow, rowCount);
        List<PurchaseTask> results = new ArrayList<>();
        for (Task task : tasks) {
            PurchaseTask vo = new PurchaseTask();
            String instanceid = task.getProcessInstanceId();
            ProcessInstance ins = runservice.createProcessInstanceQuery().processInstanceId(instanceid).singleResult();
            String businesskey = ins.getBusinessKey();
            PurchaseBpm a = purchaseservice.getPurchase(Integer.parseInt(businesskey));
            vo.setApplyer(a.getApplyer());
            vo.setApplytime(a.getApplytime());
            vo.setBussinesskey(a.getId());
            vo.setItemlist(a.getItemlist());
            vo.setProcessdefid(task.getProcessDefinitionId());
            vo.setProcessinstanceid(task.getProcessInstanceId());
            vo.setTaskid(task.getId());
            vo.setTaskname(task.getName());
            vo.setTotal(a.getTotal());
            results.add(vo);
        }
        PageVo<PurchaseTask> grid = new PageVo<>();
        grid.setCurrent(rowCount);
        grid.setRowCount(current);

        grid.setTotal((int) total);
        grid.setRows(results);
        return grid;
    }



}
